package com.didi.davinci.switcher

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.graphics.*
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import androidx.core.content.ContextCompat
import com.auto.survey.R
import java.util.*
import kotlin.collections.HashMap

/**
 * create by zhangwenbo
 * on 2022:07:14:03 下午
 * 自定义开关  支持自定义 大小  背景颜色渐变  滑动的圆形的渐变颜色
 */
class UISwitcher : View {
    companion object {
        const val DEFAULT_ANIMATION_DURATION = 150
        const val TAG = "UISwitchButton"
        const val TAG_DISABLE = "disabled"
        const val TAG_HASCHECKED = "hasChecked"
    }

    private var hasGesture: Boolean=false
    private var gestureList= LinkedList<Map<String, Boolean>>()
    private var setcheckedList= LinkedList<Map<String, Boolean>>()
    private var checkedQueueList= LinkedList<Map<String, Boolean>>()

    private var mOnCheckedChangeListener: OnCheckedChangeListener? = null
    private var backgroundDrawable: ShapeDrawable? = null
    private var thumbDrawable: ShapeDrawable? = null

    private var mProgress = 0f
    private var mTouchSlop = 0
    private var mClickTimeout = 0
    private var mProgressAnimator: ValueAnimator? = null
    private var bounds: Rect? = null
    private var bundsX = 0
    private var bgCheckedEnabledLinearGradient: LinearGradient? = null
    private var bgCheckedLinearGradient: LinearGradient? = null
    private var bgUnCheckedLinearGradient: LinearGradient? = null
    private var bgUncheckedIntermediateStateLinearGradient: LinearGradient? = null
    private var   thumbLinearGradient:LinearGradient?=null
    private var   thumbEnableLinearGradient:LinearGradient?=null

    //开关高度
    private var mHeight = 0f

    //开关宽度
    private var mWidth = 0f
    private var marginX //中间圆形距外部椭圆的距离
            = 0
    //可点击状态中间圆的颜色
    private var bgThumbStartColor = ContextCompat.getColor(context, R.color.nomal_switcher_thumb)
    private var bgThumbEndColor = ContextCompat.getColor(context, R.color.nomal_switcher_thumb)
    //不可点击状态中间圆的颜色
    private var bgThumbEnableStartColor = ContextCompat.getColor(context, R.color.disable_switcher_thumb)
    private var bgThumbEnableEndColor = ContextCompat.getColor(context, R.color.disable_switcher_thumb)

    //不可选择状态背景渐变开始颜色 以及可选择中间态选中背景开始颜色
    private var bgEnabledStartColor = ContextCompat.getColor(context, R.color.disable_switcher_off_bg)

    //不可选择状态背景渐变结束颜色 以及可选择中间态选中背景结束颜色
    private var bgEnabledEndColor = ContextCompat.getColor(context, R.color.disable_switcher_off_bg)

    //可选择状态选中背景渐变开始颜色
    private var bgCheckedStartColor = ContextCompat.getColor(context, R.color.nomal_switcher_on_bg)

    //可选择状态选中背景渐变结束颜色
    private var bgCheckedEndColor = ContextCompat.getColor(context, R.color.nomal_switcher_on_bg)

    //未选中背景颜色
    private var bgUncheckedColor = ContextCompat.getColor(context, R.color.nomal_switcher_off_bg)

    //不可选择未选中背景颜色
    private var bgUncheckedIntermediateStateColor = ContextCompat.getColor(context, R.color.disable_switcher_off_bg)

    private var hasEnabled = false //是否不可点击
    private var excuteGesture = false //是否不可点击

    private var excuteCheckedQueue = false //是否正在处理checked数据的队列

    private var hasChecked = false //是否是选中状态

    private var onTouchEventUp = true
    private var oldCheckedState = false
    private var canMove = false
    private var isSupportIntermediateState = false//是否支持中间态 中间态用户不可操作

    private var intermediateStateSupportClick = true//中间态用户是否可以操



    constructor (context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        //初始化参数
        //初始化参数
        @SuppressLint("CustomViewStyleable")
        val attr = getContext().obtainStyledAttributes(attrs, R.styleable.UiSwitchButtonStyle)
        if (attr == null) {
            mHeight = getContext().resources.getDimension(R.dimen.dp_44)
            mWidth = getContext().resources.getDimension(R.dimen.dp_24)
            initView()
            updateBackgroundColor()
            return
        }

        try {
            mWidth = attr.getDimension(
                R.styleable.UiSwitchButtonStyle_width,
                getContext().resources.getDimension(R.dimen.dp_44)
            )

            mHeight = attr.getDimension(
                R.styleable.UiSwitchButtonStyle_height,
                getContext().resources.getDimension(R.dimen.dp_24)
            )

            bgThumbStartColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_thumb_start_color,
                ContextCompat.getColor(context, R.color.nomal_switcher_thumb)
            )

            bgThumbEndColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_thumb_end_color,
                ContextCompat.getColor(context, R.color.nomal_switcher_thumb)
            )

            bgThumbEnableStartColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_thumb_enable_start_color,
                ContextCompat.getColor(context, R.color.disable_switcher_thumb)
            )

            bgThumbEnableEndColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_thumb_enable_end_color,
                ContextCompat.getColor(context, R.color.disable_switcher_thumb)
            )

            bgEnabledStartColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_enabled_start_color,
                ContextCompat.getColor(context, R.color.disable_switcher_on_bg)
            )
            bgEnabledEndColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_enabled_end_color,
                ContextCompat.getColor(context, R.color.disable_switcher_on_bg)
            )

            bgUncheckedColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_unchecked_color,
                ContextCompat.getColor(context, R.color.nomal_switcher_off_bg)
            )

            bgUncheckedIntermediateStateColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_unchecked_intermediate_state_color,
                ContextCompat.getColor(context, R.color.disable_switcher_off_bg)
            )

            bgCheckedStartColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_checked_start_color,
                ContextCompat.getColor(context, R.color.nomal_switcher_on_bg)
            )

            bgCheckedEndColor = attr.getColor(
                R.styleable.UiSwitchButtonStyle_checked_end_color,
                ContextCompat.getColor(context, R.color.nomal_switcher_on_bg)
            )


            isSupportIntermediateState = attr.getBoolean(
                R.styleable.UiSwitchButtonStyle_support_intermediate_state,
                false
            )
        } finally {
            attr.recycle()
        }
        initView()
        updateBackgroundColor()
    }

    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        updateBackgroundColor()
    }

    private fun initView() {
        val radius = mHeight / 2
        marginX = context.resources.getDimension(R.dimen.dp_2).toInt()
        //系统的最小滑动距离  按下时间
        mTouchSlop = ViewConfiguration.get(context).scaledWindowTouchSlop
        mClickTimeout =
            ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout()

//        mTouchSlop = 20;
//        mClickTimeout = 200;
        mProgressAnimator = ValueAnimator()
        //背景颜色以及圆角
        val outerRadius = floatArrayOf(
            radius,
            radius,
            radius,
            radius,
            radius,
            radius,
            radius,
            radius
        ) //外矩形 左上、右上、右下、左下的圆角半径
        val inset = RectF(0f, 0f, 0f, 0f) //内矩形距外矩形，左上角x,y距离， 右下角x,y距离
        val innerRadii = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) //内矩形 圆角半径
        val roundRectShape = RoundRectShape(outerRadius, inset, innerRadii)
        backgroundDrawable = ShapeDrawable(roundRectShape)
        bgCheckedEnabledLinearGradient = LinearGradient(
            0f,
            0f,
            mWidth,
            mHeight,
            bgEnabledStartColor,
            bgEnabledEndColor,
            Shader.TileMode.REPEAT
        )
        bgCheckedLinearGradient = LinearGradient(
            0f,
            0f,
            mWidth,
            mHeight,
            bgCheckedStartColor,
            bgCheckedEndColor,
            Shader.TileMode.REPEAT
        )
        bgUnCheckedLinearGradient = LinearGradient(
            0f,
            0f,
            mWidth,
            mHeight,
            bgUncheckedColor,
            bgUncheckedColor,
            Shader.TileMode.REPEAT
        )
        bgUncheckedIntermediateStateLinearGradient = LinearGradient(
            0f,
            0f,
            mWidth,
            mHeight,
            bgUncheckedIntermediateStateColor,
            bgUncheckedIntermediateStateColor,
            Shader.TileMode.REPEAT
        )
        backgroundDrawable!!.setBounds(0, 0, mWidth.toInt(), mHeight.toInt())

        //内部滑动圆形
        val thumbInset = RectF(0f, 0f, 0f, 0f)
        val shape = RoundRectShape(outerRadius, thumbInset, outerRadius)
        //渐变色计算类
         thumbLinearGradient = LinearGradient(
            0f,
            0f,
            mHeight,
            mHeight,
            bgThumbStartColor,
            bgThumbEndColor,
            Shader.TileMode.REPEAT
        )
        thumbEnableLinearGradient = LinearGradient(
            0f,
            0f,
            mHeight,
            mHeight,
            bgThumbEnableStartColor,
            bgThumbEnableEndColor,
            Shader.TileMode.REPEAT
        )
        thumbDrawable = ShapeDrawable(shape)
        thumbDrawable!!.paint.shader = thumbLinearGradient
        thumbDrawable!!.paint.style = Paint.Style.FILL
        bundsX = (mProgress * (mWidth - mHeight)).toInt()
        bounds = Rect(marginX, marginX, (mHeight - marginX).toInt(), (mHeight - marginX).toInt())
        thumbDrawable!!.bounds = bounds as Rect
    }

    private fun getProgress(): Float {
        return mProgress
    }

    private fun setProcess(progress: Float) {
        var tp = progress
        if (tp > 1) {
            tp = 1f
        } else if (tp < 0) {
            tp = 0f
        }
        Log.d(TAG, "progress = $tp")
        updatePaintStyle(tp, false)
        mProgress = tp
        bundsX = (mProgress * (mWidth - mHeight)).toInt()
        Log.d(TAG, "setProcess ===> bundsX = $bundsX marginX = $marginX")
        bounds!!.left = bundsX + marginX
        Log.d(TAG, "setProcess ===> bounds!!.left = ${bounds!!.left}")
        bounds!!.right = (mHeight + bundsX - marginX).toInt()
        Log.d(TAG, "setProcess ===> bounds!!.right = ${bounds!!.right}")
        thumbDrawable!!.bounds = bounds as Rect
        invalidate()
    }

    private fun updatePaintStyle(tp: Float, isClick: Boolean) {
        if (!isClick) {
            hasChecked = tp > 0.5f
            Log.d(TAG, "func: updatePaintStyle --->hasChecked=$hasChecked")
        }
        updateBackgroundColor()
    }

    private var mStartX = 0f
    private var mStartY = 0f
    private var mLastX = 0f


    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {

        //触碰控件时，不应该允许setCheckedState();
        hasGesture=true
        Log.d(TAG, "onTouchEvent--------->${event.action}, hasGesture=$hasGesture")
        if(event.action==MotionEvent.ACTION_UP|| event.action==MotionEvent.ACTION_CANCEL){
            hasGesture=false
            Log.d(TAG, "event.action==MotionEvent.ACTION_UP|| event.action==MotionEvent.ACTION_CANCEL--------->${event.action}, hasGesture=$hasGesture")
        }

        Log.d(TAG, "excuteGesture = $excuteGesture")
       if (excuteGesture) {
           Log.d(TAG, "============excuteGesture")
           if(event.action==MotionEvent.ACTION_UP|| event.action==MotionEvent.ACTION_CANCEL){
               Log.d(TAG, "============event.action==MotionEvent.ACTION_UP|| event.action==MotionEvent.ACTION_CANCE")
               excuteGesture=false;
           }
            return true
       }

        if (hasEnabled) {
            Log.d(TAG, "============hasEnabled = $hasEnabled")
            return true
        }

        if (!intermediateStateSupportClick) {
            Log.d(TAG, "============哈哈我不可以点击了 intermediateStateSupportClick = $intermediateStateSupportClick")
//            if (!lastDisabled) {
//                intermediateStateSupportClick = true
//            }
            return true
        }

        val action = event.action
        val deltaX = event.x - mStartX
        val deltaY = event.y - mStartY
        val pointXStart = (thumbDrawable!!.bounds.centerX() - height / 2).toFloat()
        val pointXEnd = (thumbDrawable!!.bounds.centerX() + height / 2).toFloat()
//        Log.d(TAG, "onTouchEvent action$action   deltaX=$deltaX  deltaY$deltaY pointXStart$pointXStart pointXEnd$pointXEnd  event.x$event.x  event.y$event.y")
        when (action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "ACTION_DOWN   canmove$canMove")
                canMove = event.x in pointXStart..pointXEnd
                oldCheckedState = hasChecked
                onTouchEventUp = false
                mStartX = event.x
                mStartY = event.y
                mLastX = mStartX
                isPressed = true
            }
            MotionEvent.ACTION_MOVE -> {
                Log.d(TAG, "ACTION_MOVE   canmove$canMove")
                if (canMove) {
                    onTouchEventUp = false
                    val x = event.x
                    //计算滑动的比例 boundsWidth为整个宽度的一半
                    setProcess(getProgress() + (x - mLastX) / mHeight)
                    //这里比较x轴方向的滑动 和y轴方向的滑动 如果y轴大于x轴方向的滑动 事件就不在往下传递
                    if (Math.abs(deltaX) > mTouchSlop / 2 || Math.abs(deltaY) > mTouchSlop / 2) {
                        if (Math.abs(deltaY) > Math.abs(deltaX)) {
                            return false
                        }
                    }
                    mLastX = x
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                onTouchEventUp = true
                hasGesture=false
                isPressed = false


                //计算从手指触摸到手指抬起时的时间
                val time = (event.eventTime - event.downTime).toFloat()
                Log.d(TAG, "time = $time")
                //如果x轴和y轴滑动距离小于系统所能识别的最小距离 切从手指按下到抬起时间 小于系统默认的点击事件触发的时间  整个行为将被视为触发点击事件
                if (Math.abs(deltaX) < mTouchSlop && Math.abs(deltaY) < mTouchSlop && time < mClickTimeout) {
                    //如果是点击事件则选中状态为当前状态的相反状态
                    hasChecked = !hasChecked
                    Log.d(TAG, "####hasChecked=$hasChecked")
                    animateToState(hasChecked, true)
                    if (isSupportIntermediateState) {
                        Log.d(TAG, "用户可以操作了============+++++++++++++++++++++isSupportIntermediateState = $isSupportIntermediateState, intermediateStateSupportClick = $intermediateStateSupportClick")
                        intermediateStateSupportClick = false
                    }
                    if (mOnCheckedChangeListener != null) {
                        Log.d(TAG,"当前开关状态 $hasChecked")
                        mOnCheckedChangeListener!!.onCheckedChanged(this, hasChecked)
                    }
                    Log.d(TAG, "ACTION_UP   点击事件")
                    excuteQueue();
                    return false
                } else {
                    val nextStatus = getProgress() > 0.5f
                    Log.d(TAG, "####nextStatus=$nextStatus, hasChecked=$hasChecked, oldCheckedState = $oldCheckedState")
                    animateToState(nextStatus, false)
                    if (mOnCheckedChangeListener != null && hasChecked != oldCheckedState) {
                        if (isSupportIntermediateState) {
                            Log.d(TAG, "用户可以操作了============+++++++++++++++++++++isSupportIntermediateState = $isSupportIntermediateState, intermediateStateSupportClick = $intermediateStateSupportClick")
                            intermediateStateSupportClick = false
                        }
                        Log.d(TAG,"当前开关状态 $hasChecked")
                        mOnCheckedChangeListener!!.onCheckedChanged(this, hasChecked)
                    }
                    Log.d(TAG, "ACTION_UP   触摸事件")
                    excuteQueue();
                }

            }
        }
        return true
    }

    private fun excuteQueue() {
        Log.d(TAG, "开始处理队列手势数据：func excuteQueue list.size  =${gestureList.size}")
        if (gestureList.size > 0) {

            excuteGesture=true
            if (isSupportIntermediateState) {
                intermediateStateSupportClick = true
            }

            cancelAnimation()
            var disabled:Boolean = gestureList.last[TAG_DISABLE] == true
            var hasChecked:Boolean  = gestureList.last[TAG_HASCHECKED] == true
            Log.d(TAG, "func excuteQueue 队列进来了disabled=$disabled, hasChecked =$hasChecked")
            setSingleState(disabled, hasChecked)
            gestureList.clear()
            excuteGesture=false;
        }
    }

    private fun excuteCheckedQueue() {
        Log.d(TAG, "开始处理队列普通数据：func excuteQueue list.size  =${setcheckedList.size}")

        if (setcheckedList.size > 0) {
            excuteCheckedQueue = true

            if (isSupportIntermediateState) {
                intermediateStateSupportClick = true
            }

            cancelAnimation()
            var disabled:Boolean = setcheckedList.last[TAG_DISABLE] == true
            var hasChecked:Boolean  = setcheckedList.last[TAG_HASCHECKED] == true
            setSingleState(disabled, hasChecked)
            setcheckedList.clear()
            excuteCheckedQueue = false
        }
    }

    private fun animateToState(checked: Boolean, isClick: Boolean) {
        val progress = mProgress
        Log.d(TAG, "func:animateToState ----> progress = $progress")
        if (cancelAnimation()) return
        mProgressAnimator!!.duration = DEFAULT_ANIMATION_DURATION.toLong()
        if (checked) {
            mProgressAnimator!!.setFloatValues(progress, 1f)
        } else {
            mProgressAnimator!!.setFloatValues(progress, 0.0f)
        }


        mProgressAnimator!!.addUpdateListener { animation ->
            mProgress = animation.animatedValue as Float
            updatePaintStyle(mProgress, isClick)
            bundsX = (mProgress * (mWidth - mHeight)).toInt()
            bounds!!.left = bundsX + marginX
            bounds!!.right = (mHeight + bundsX - marginX).toInt()
            thumbDrawable!!.bounds = bounds as Rect
            postInvalidate()
        }
        mProgressAnimator!!.start()

    }

    private fun cancelAnimation(): Boolean {
        if (mProgressAnimator == null) {
            return true
        }
        if (mProgressAnimator!!.isRunning) {
            mProgressAnimator!!.cancel()
        }
        mProgressAnimator!!.removeAllUpdateListeners()
        return false
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(mWidth.toInt(), mHeight.toInt())
    }



    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (canvas != null) {
            backgroundDrawable!!.draw(canvas)
        }
        if (canvas != null) {
            thumbDrawable!!.draw(canvas)
        }
    }

    /**
     * 设置当前开关是否不可操作  以及开关状态
     *
     * @param disabled true 不可操作  false可操作
     * @param hasChecked true 开  false 关
     */
    fun setCheckedState(disabled: Boolean, hasChecked: Boolean) {
        if (disabled && hasChecked) {
            Log.d(TAG, "打开中间状态 disabled= $disabled, hasChecked = $hasChecked")
        }  else if (disabled && !hasChecked) {
            Log.d(TAG, "停止录制中间态 disabled= $disabled, hasChecked = $hasChecked")
        } else if (!disabled && hasChecked) {
            Log.d(TAG, "开始录制 disabled= $disabled, hasChecked = $hasChecked")
        } else if (!disabled && !hasChecked) {
            Log.d(TAG, "未选中状态 disabled= $disabled, hasChecked = $hasChecked")
        }
        excuteGesture = true

        if (isSupportIntermediateState) {
            intermediateStateSupportClick = true
        }
        hasEnabled = disabled
        this.hasChecked = hasChecked
//        setSingleState(disabled, hasChecked)
        if(hasGesture){
            excuteGesture=false
            Log.d(TAG, "开始添加队列")
            var map = HashMap<String, Boolean>()
            map[TAG_DISABLE] = disabled
            map[TAG_HASCHECKED] = hasChecked
            gestureList.add(map)
            return
        }

//        else {
//            settingChecked(disabled, hasChecked)
//            //如果当前队列正在执行
//            excuteCheckedQueue()
//        }

        Log.d(TAG, "func:setCheckedState => 设置当前开关状态 disabled=$disabled, hasChecked = $hasChecked, isSupportIntermediateState = $isSupportIntermediateState, intermediateStateSupportClick = $intermediateStateSupportClick")
        setSingleState(disabled, hasChecked)
        Log.d(TAG, "func:setCheckedState => ============hasGesture= $hasGesture")
        if(!hasGesture){
            excuteGesture=false
        }
    }


    private fun settingChecked(disabled: Boolean, hasChecked: Boolean) {
        var map = HashMap<String, Boolean>()
        map[TAG_DISABLE] = disabled
        map[TAG_HASCHECKED] = hasChecked
        checkedQueueList.add(map)
        if (excuteCheckedQueue) {
            settingChecked(disabled, hasChecked)
        } else {
            setcheckedList.addAll(checkedQueueList)
            checkedQueueList.clear()
        }
    }

    private fun setSingleState(disabled: Boolean, hasChecked: Boolean) {
        Log.d(TAG, "设置switcher是否是开启 还是关闭")
        setProcess(if (hasChecked) 1f else 0f)
    }

    private fun updateBackgroundColor() {
        Log.d(TAG, "func:updateBackgroundColor--> hasEnabled=$hasEnabled, hasChecked = $hasChecked, " +
                "onTouchEventUp = $onTouchEventUp ， isSupportIntermediateState=$isSupportIntermediateState , intermediateStateSupportClick = $intermediateStateSupportClick")
        if (hasEnabled) {
            if (hasChecked) {
                backgroundDrawable!!.paint.shader = bgCheckedEnabledLinearGradient
            } else {
                backgroundDrawable!!.paint.shader = bgUncheckedIntermediateStateLinearGradient
            }
            thumbDrawable!!.paint.shader=thumbEnableLinearGradient
        } else {
            if (onTouchEventUp) {
                if (hasChecked) {
                    if (isSupportIntermediateState && !intermediateStateSupportClick) {
                        backgroundDrawable!!.paint.shader = bgCheckedEnabledLinearGradient
                        thumbDrawable!!.paint.shader=thumbEnableLinearGradient
                    }else{
                        backgroundDrawable!!.paint.shader = bgCheckedLinearGradient
                        thumbDrawable!!.paint.shader=thumbLinearGradient
                    }
                } else {
                    if (isSupportIntermediateState && !intermediateStateSupportClick)
                    {
                        backgroundDrawable!!.paint.shader = bgUncheckedIntermediateStateLinearGradient
                        thumbDrawable!!.paint.shader=thumbEnableLinearGradient
                    }else{
                        backgroundDrawable!!.paint.shader = bgUnCheckedLinearGradient
                        thumbDrawable!!.paint.shader=thumbLinearGradient
                    }
                }
            } else {
                if (oldCheckedState) {
                    backgroundDrawable!!.paint.shader = bgCheckedLinearGradient
                } else {
                    backgroundDrawable!!.paint.shader = bgUnCheckedLinearGradient
                }
                thumbDrawable!!.paint.shader=thumbLinearGradient
            }
        }
    }


    /**
     * 获取当前开关是否开
     *
     * @return true 开  false 关
     */
    fun isChecked(): Boolean {
        return hasChecked
    }

    /**
     *  是否需要展示中间状态
     */
    fun setSupportIntermediateState(middleStatus: Boolean) {
        Log.d(TAG, "func : setSupportIntermediateState   middleStatus = $middleStatus, isSupportIntermediateState = $isSupportIntermediateState")
        isSupportIntermediateState = middleStatus
    }

    /**
     * 设置当前开关 开 关
     *
     * @param isChecked true 开  false 关
     */
    fun setCheckedState(isChecked: Boolean) {
        Log.d(TAG, "func : setCheckedState   intermediateStateSupportClick = $intermediateStateSupportClick, isSupportIntermediateState = $isSupportIntermediateState")
        if (isSupportIntermediateState) {
            intermediateStateSupportClick = true
        }
        hasChecked = isChecked
        setProcess(if (hasChecked) 1f else 0f)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (mProgressAnimator == null) {
            return
        }
        if (mProgressAnimator!!.isRunning) {
            mProgressAnimator!!.cancel()
            mProgressAnimator!!.removeAllUpdateListeners()
        }
    }

    /**
     * 中间按钮的渐变开始颜色
     */
    fun setBgThumbStartColor(bgThumbStartColor: Int): UISwitcher {
        this.bgThumbStartColor = bgThumbStartColor
        return this
    }


    /**
     * 中间按钮的渐变结束颜色
     */
    fun setBgThumbEndColor(bgThumbEndColor: Int): UISwitcher {
        this.bgThumbEndColor = bgThumbEndColor
        return this
    }

    /**
     * 不可点击中间按钮的渐变开始颜色
     */
    fun setBgThumbEnableStartColor(bgThumbEnableStartColor: Int): UISwitcher {
        this.bgThumbEnableStartColor = bgThumbEnableStartColor
        return this
    }

    /**
     * 不可点击中间按钮的渐变结束颜色
     */
    fun setBgThumbEnableEndColor(bgThumbEnableEndColor: Int): UISwitcher {
        this.bgThumbEnableEndColor = bgThumbEnableEndColor
        return this
    }

    /**
     * 不可选择状态背景渐变开始颜色   以及可选择中间态选中背景开始颜色
     */
    fun setBgEnabledStartColor(bgEnabledStartColor: Int): UISwitcher {
        this.bgEnabledStartColor = bgEnabledStartColor
        return this
    }

    /**
     * 不可选择状态背景渐变结束颜色   以及可选择中间态选中背景结束颜色
     */
    fun setBgEnabledEndColor(bgEnabledEndColor: Int): UISwitcher {
        this.bgEnabledEndColor = bgEnabledEndColor
        return this
    }

    /**
     * 可选择状态选中背景渐变开始颜色
     */
    fun setBgCheckedStartColor(bgCheckedStartColor: Int): UISwitcher {
        this.bgCheckedStartColor = bgCheckedStartColor
        return this
    }
    /**
     * 可选择状态选中背景渐变结束颜色
     */
    fun setBgCheckedEndColor(bgCheckedEndColor: Int): UISwitcher {
        this.bgCheckedEndColor = bgCheckedEndColor
        return this
    }

    /**
     * 未选中背景颜色
     */
    fun setBgUncheckedColor(bgUncheckedColor: Int): UISwitcher {
        this.bgUncheckedColor = bgUncheckedColor
        return this
    }

    override fun canScrollHorizontally(direction: Int): Boolean {
        return true
    }

    /**
     * 未选中中间态背景颜色
     */
    fun setBgUncheckedIntermediateStateColor(bgUncheckedIntermediateStateColor: Int): UISwitcher {
        this.bgUncheckedIntermediateStateColor = bgUncheckedIntermediateStateColor
        return this
    }

    /**
     * 高度
     */
    fun setHeight(height: Float): UISwitcher {
        this.mHeight = height
        return this
    }

    /**
     * 宽度
     */
    fun setWidth(width: Float): UISwitcher {
        this.mWidth = width
        return this
    }

    fun build() {
        //执行刷新
        initView()
        setProcess(if (hasChecked) 1f else 0f)
    }

    fun interface OnCheckedChangeListener {
        /**
         * Called when the checked state of a compound button has changed.
         *
         * @param buttonView The compound button view whose state has changed.
         * @param isChecked  The new checked state of buttonView.
         */
        fun onCheckedChanged(buttonView: UISwitcher, isChecked: Boolean)
    }

    fun setOnCheckedChangeListener(listener: OnCheckedChangeListener) {
        mOnCheckedChangeListener = listener
    }
}
